<template>
  <div class="wang-editor">
    <Toolbar class="editor-toolbar" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor class="editor-content" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
      @onCreated="handleCreated" @onChange="handleChange" style="height: 100%" />
  </div>
</template>

<script setup>
import { ref, shallowRef, onBeforeUnmount, watch } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import request from '@/utils/request'
const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  mode: {
    type: String,
    default: 'default'
  },
  height: {
    type: Number,
    default: 300
  }
})

const emit = defineEmits(['update:value', 'change'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')

// 模拟 ajax 异步获取内容
watch(() => props.value, (val) => {
  valueHtml.value = val
}, { immediate: true })
// 编辑器配置
const editorConfig = ref({
  placeholder: '请输入内容...',
  MENU_CONF: {},
  autoFocus: false,
  readOnly: props.mode === 'preview',
  scroll: false, // 禁用编辑器的滚动
  height: props.height, // 设置编辑器高度, 

})
const uploadConfig = {
  // 自定义增加 http  header
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  // 自定义图片上传
  async customUpload(file, insertFn) {
    // file 即选中的文件
    const fd = new FormData()
    fd.append('file', file)
    const formData = new FormData()
    formData.append('file', file)
    try {
      const res = await request.post('/upload', formData)
      console.log(res)
      if (res.length) {
        insertFn(res[0].url)
      }

    } catch (error) {
      console.log(error) 
    }
  },
}
editorConfig.value.MENU_CONF.uploadImage = uploadConfig
editorConfig.value.MENU_CONF.uploadVideo = uploadConfig
// 工具栏配置
const toolbarConfig = {
  excludeKeys: [] // 可以在这里配置不需要显示的工具栏按钮
}



// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例
}

const handleChange = (editor) => {
  emit('update:value', editor.getHtml())
  emit('change', editor.getHtml())
}

</script>

<style lang="scss" scoped>
.wang-editor {
  border: 1px solid #eee;
  z-index: 100;
  display: flex;
  flex-direction: column;
  height: 100%;

  :deep(.editor-toolbar) {
    border-bottom: 1px solid #eee;
    flex-shrink: 0;
  }

  :deep(.editor-content) {
    flex: 1;
    overflow-y: auto;

    .w-e-text-container {
      height: calc(v-bind('props.height') * 1px - 40px) !important;
      background-color: #fff;
    }

    .w-e-scroll {
      height: 100% !important;
      min-height: unset !important;
    }
  }
}
</style>